package com.kang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kang.Vo.PhotoVo;
import com.kang.commons.Result;
import com.kang.commons.util.MapToObjUtil;
import com.kang.commons.util.QiniuUtil;
import com.kang.commons.util.RedisUtil;
import com.kang.bean.GroupS;
import com.kang.bean.Photo;
import com.kang.bean.Users;
import com.kang.mapper.GroupMapper;
import com.kang.mapper.PhotoMapper;
import com.kang.service.PhotoService;
import com.kang.service.UserService;
import com.kang.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * @program: photo_fawu
 * @description: 服务层
 * @author: K.faWu
 * @create: 2021-10-25 15:22
 **/

@Service
@Slf4j
public class PhotoServiceImpl extends ServiceImpl<PhotoMapper, Photo> implements PhotoService {

    @Autowired
    private PhotoMapper photoMapper;
    @Autowired
    private QiniuUtil qiniuUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private GroupMapper groupMapper;
    @Autowired
    private UsersService usersService;

    @Override
    public String uploadPhoto(MultipartFile file, Integer groupId) {
        //文件名
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //获取后缀名
        int i = originalFilename.lastIndexOf(".");
        String endName = originalFilename.substring(i);
        endName = endName.toLowerCase();
        //判断是否是指定类
        List<String> fileType = Arrays.asList(".gif", ".jpg", ".jfif", ".ico", ".png", ".bmp", ".svg");
        if (!fileType.contains(endName)) {
            Result.error("文件类型错误");
        }
        try {
            String path = qiniuUtil.setUploadManager(file.getInputStream());
            if (path == null){
                Result.error("输入的字符不能为空！");
            }
            Photo photo = new Photo();
            //获取文件名
            String name = originalFilename.split("\\.")[0];
            photo.setName(name);
            photo.setGroupId(groupId);
            photo.setPath(path);
            photoMapper.insert(photo);
            return path;
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("文件上传失败");
        }
        return null;
    }

    @Override
    public PhotoVo queryByGroupId(Long groupId, HttpServletRequest request) {
        PhotoVo photoVo = new PhotoVo();
        Result<Users> result = usersService.getUsers2(request.getHeader("token"));
        Users users = result.getData();
        if (users != null) {
            QueryWrapper<Photo> wrapper = new QueryWrapper<>();
            wrapper.eq("group_id", groupId);
            List<Photo> list = photoMapper.selectList(wrapper);
            ArrayList<String> urlList = new ArrayList<>();
            list.forEach(photo -> {
                //获取用户是否点赞
                ZSetOperations<String, Object> zSet = redisTemplate.opsForZSet();
                Double score = zSet.score(photo.getId().toString(), users.getId());
                if (score != null && score != 0) {
                    photo.setInfo(score.toString());
                }
                //或者该照片被点赞的数量
                Double photoScore = zSet.score("photo", photo.getId());
                photo.setLikes(photoScore == null ? 0 : photoScore.longValue());
                urlList.add(photo.getPath());
            });
            photoVo.setPhotoList(list);
            photoVo.setUrlList(urlList);
        }
        return photoVo;
    }

    @Override
    public void deleteById(Long id) {
        ZSetOperations<String, Object> zSet = redisTemplate.opsForZSet();
        zSet.remove("photo",id);
        Photo photo = photoMapper.selectById(id);
        qiniuUtil.deleteFile(photo.getPath());
        photoMapper.deleteById(id);
    }

    @Override
    public Photo like(Photo photo, HttpServletRequest request) {
        //获取当前点赞的用户
        Users users = userService.getUsers(request);
        if (users == null){
            Result.error("您未登录或登录已过期！");
        }
        ZSetOperations<String, Object> zSet = redisTemplate.opsForZSet();
        Double score = zSet.score(photo.getId().toString(), users.getId());
        Double photoScore = zSet.score("photo", photo.getId());
        if (score == null || score == 0){
            //限制用户重复点赞
            zSet.add(photo.getId().toString(), users.getId(), score==null?1 :score+1);
            photo.setInfo("1");
            //存放照片的点赞次数
            zSet.add("photo",photo.getId(),photoScore==null? 1: photoScore+1);
            photo.setLikes(photoScore.longValue()+1);
        }else {
            //如果已经赞过了再点击就是取消
            zSet.add(photo.getId().toString(), users.getId(), score-1);
            photo.setInfo("0");
            zSet.add("photo",photo.getId(),photoScore==null? 0: photoScore-1);
            photo.setLikes(photoScore.longValue()-1);
        }
        return photo;
    }

    @Override
    public PhotoVo showPhoto() {
        ZSetOperations<String, Object> zSet = redisTemplate.opsForZSet();
        Set<Object> set = zSet.range("photo", zSet.zCard("photo")-5, zSet.zCard("photo"));
        ArrayList<Photo> photos = new ArrayList<>();
        set.forEach(obj ->{
            Long id = (Long) obj;
            Photo photo = photoMapper.selectById(id);
            if (photo!=null){
                Double score = zSet.score("photo", photo.getId());
                photo.setLikes(score.longValue());
                photos.add(photo);
            }
        });
        PhotoVo photoVo = new PhotoVo();
        photoVo.setPhotoList(photos);
        return photoVo;
    }

    /**
     * 刷新每日点赞
     */
    @Override
    public void saveLikePhoto() {
        log.info("定时清空点赞");
        ZSetOperations<String, Object> zSet = redisTemplate.opsForZSet();
        List<Photo> list = photoMapper.selectList(new QueryWrapper<>());
        list.forEach(photo -> zSet.removeRange(photo.getId().toString(),0, 10));

    }

    @Override
    public void deleteList(List<Photo> photoList, HttpServletRequest request) {
        Result<Users> result = usersService.getUsers2(request.getHeader("token"));
        Users users =result.getData();
        if (ObjectUtils.isEmpty(users)){
            Result.error("未登录！");
        }
        GroupS groupS = groupMapper.selectById(photoList.get(0).getGroupId());
        if (users.getId()-groupS.getUserId() != 0){
            Result.error("您试图删除别人的照片！");
        }
        photoList.forEach(photo -> this.deleteById(photo.getId()));
    }

}
